package app.mvp.utils;

import android.Manifest;
import android.annotation.TargetApi;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.provider.DocumentsContract;
import android.provider.MediaStore;
import android.support.annotation.RequiresApi;
import android.support.v4.content.FileProvider;
import android.text.TextUtils;
import android.util.Log;
import android.widget.FrameLayout;
import android.widget.Toast;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import app.photolibrary.MultiImageSelectorActivity;
import app.photolibrary.utils.BitmapUtils;
import utils.ToastUtils;


/**
 * Created by 刘智强 on 2017/5/15.
 * 关于拍照和选取照片的工具类
 */

public class PhotoUtils {
    public final int TAKE_PHOTO = 1;//拍照

    public final int CHOOSE_PHOTO = 2;//选取照片

    public final int CROP_PHOTO = 3;//裁剪

    public final int CHOOSE_MUTIL_PHOTOS = 4;//选取多张照片
    //一次最多选取照片的数量
    private final int maxNum = 30;
    //多张照片路径的集合
    private ArrayList<String> mSelectPath;
    //多张照片bitmap集合
    private List<Bitmap> bitmapList = new ArrayList<>();
    //最终装照片路径的集合
    private List<String> finalSelectPaths = new ArrayList<>();
    //7.0  ContentUri
    public final String FILE_CONTENT_FILEPROVIDER = "app.mvp.fileprovider";//provider的authorities属性

    //相机拍照默认存储路径
    public final String PICTURE_DIR = Environment.getExternalStorageDirectory() + "/bao/pictures/";
    //APP名字
    public final String APP_NAME = "bao";
    //日期
    public String DATE = "";
    //截图图片名
    private String crop_image;
    private PhotoListener photoListener;
    private static PhotoUtils instance;
    private Bitmap bitmap;

    //照片图片名
    private String photo_image;

    private boolean isCrop = false;//是否要裁剪图片

    public static PhotoUtils getInstance() {
        if (instance == null) {
            synchronized (PhotoUtils.class) {
                if (instance == null) {
                    instance = new PhotoUtils();
                }
            }
        }
        return instance;
    }


    /**
     * 拍照
     *
     * @param mActivity
     */
    public void takePhoto(Activity mActivity, boolean isCrop, PhotoListener photoListener) {
        this.photoListener = photoListener;
        this.isCrop = isCrop;
        XPermissionUtils.requestPermissions(mActivity, XPermissionUtils.MORE, new String[]{
                android.Manifest.permission.CAMERA, Manifest.permission.READ_EXTERNAL_STORAGE}, new XPermissionUtils.OnPermissionListener() {
            @Override
            public void onPermissionGranted() {
                //允许
                Log.e("TAG", "允许拍照");
                openCamera(mActivity);
            }

            @Override
            public void onPermissionDenied(String[] deniedPermissions, boolean alwaysDenied) {
                Log.e("TAG", "被拒绝");
                Toast.makeText(mActivity, "拒绝拍照", Toast.LENGTH_SHORT).show();
                Log.e("TAG", alwaysDenied + "");
                if (alwaysDenied) {
                    //拒绝后不再提示，一般跳转到设置页面
                    XPermissionUtils.getAppDetailSettingIntent(mActivity);
                } else {
                    //被拒绝，还可以再次请求获取该权限
                    new AlertDialog.Builder(mActivity).setTitle("温馨提示")
                            .setMessage("我们需要相机权限才能正常使用该功能")
                            .setNegativeButton("取消", null)
                            .setPositiveButton("验证权限", new DialogInterface.OnClickListener() {
                                @RequiresApi(api = Build.VERSION_CODES.M)
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    XPermissionUtils.requestPermissionsAgain(mActivity, deniedPermissions, XPermissionUtils.CAMERA);
                                }
                            }).show();
                }
            }


        }, new XPermissionUtils.RationaleHandler() {
            @Override
            protected void showRationale() {
                Log.e("TAG", "被拒绝，再次申请");
                requestPermissionsAgain();

            }
        });


    }

    /**
     * 从 相册选取单张照片
     *
     * @param mActivity
     * @param isCrop
     * @param photoListener
     */
    public void choosePhoto(Activity mActivity, boolean isCrop, PhotoListener photoListener) {
        this.photoListener = photoListener;
        this.isCrop = isCrop;
        XPermissionUtils.requestPermissions(mActivity, XPermissionUtils.MORE, new String[]{
                android.Manifest.permission.CAMERA, Manifest.permission.READ_EXTERNAL_STORAGE}, new XPermissionUtils.OnPermissionListener() {
            @Override
            public void onPermissionGranted() {
                //允许
                openAlbum(mActivity);
            }

            @Override
            public void onPermissionDenied(String[] deniedPermissions, boolean alwaysDenied) {
                Log.e("TAG", "被拒绝");
                Toast.makeText(mActivity, "拒绝拍照", Toast.LENGTH_SHORT).show();
                if (alwaysDenied) {
                    XPermissionUtils.getAppDetailSettingIntent(mActivity);

                } else {
                    //被拒绝，还可以再次请求获取该权限
                    new AlertDialog.Builder(mActivity).setTitle("温馨提示")
                            .setMessage("我们需要相机权限才能正常使用该功能")
                            .setNegativeButton("取消", null)
                            .setPositiveButton("验证权限", new DialogInterface.OnClickListener() {
                                @RequiresApi(api = Build.VERSION_CODES.M)
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    XPermissionUtils.requestPermissionsAgain(mActivity, deniedPermissions, XPermissionUtils.CAMERA);
                                }
                            })
                            .show();

                }
            }
        }, new XPermissionUtils.RationaleHandler() {
            @Override
            protected void showRationale() {
                Log.e("TAG", "被拒绝，再次申请");
                requestPermissionsAgain();
            }
        });


    }

    /**
     * 从相册选取多张图片
     */
    public void chooseMultiImage(Activity mActivity, PhotoListener photoListener) {
        this.photoListener = photoListener;
        XPermissionUtils.requestPermissions(mActivity, XPermissionUtils.MORE, new String[]{
                android.Manifest.permission.CAMERA, Manifest.permission.READ_EXTERNAL_STORAGE}, new XPermissionUtils.OnPermissionListener() {
            @Override
            public void onPermissionGranted() {
                selectGallery(mActivity);

            }

            @Override
            public void onPermissionDenied(String[] deniedPermissions, boolean alwaysDenied) {

                Log.e("TAG", "被拒绝");
                Toast.makeText(mActivity, "拒绝拍照", Toast.LENGTH_SHORT).show();
                if (alwaysDenied) {
                    XPermissionUtils.getAppDetailSettingIntent(mActivity);

                } else {
                    //被拒绝，还可以再次请求获取该权限
                    new AlertDialog.Builder(mActivity).setTitle("温馨提示")
                            .setMessage("我们需要相机权限才能正常使用该功能")
                            .setNegativeButton("取消", null)
                            .setPositiveButton("验证权限", new DialogInterface.OnClickListener() {
                                @RequiresApi(api = Build.VERSION_CODES.M)
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    XPermissionUtils.requestPermissionsAgain(mActivity, deniedPermissions, XPermissionUtils.CAMERA);
                                }
                            })
                            .show();

                }

            }
        }, new XPermissionUtils.RationaleHandler() {
            @Override
            protected void showRationale() {
                Log.e("TAG", "被拒绝，再次申请");
                requestPermissionsAgain();
            }
        });

    }

    /**
     * 跳转到选取多张照片的界面
     *
     * @param mActivity
     */

    private void selectGallery(Activity mActivity) {
        Intent intent = new Intent(mActivity, MultiImageSelectorActivity.class);
        // 是否显示拍摄图片,显示
        intent.putExtra(MultiImageSelectorActivity.EXTRA_SHOW_CAMERA, true);
        // 最大可选择图片数量 30张
        intent.putExtra(MultiImageSelectorActivity.EXTRA_SELECT_COUNT, maxNum);
        // 选择模式,选取多张
        intent.putExtra(MultiImageSelectorActivity.EXTRA_SELECT_MODE, MultiImageSelectorActivity.MODE_MULTI);
        // 默认选择
        if (mSelectPath != null && mSelectPath.size() > 0) {
            intent.putExtra(MultiImageSelectorActivity.EXTRA_DEFAULT_SELECTED_LIST, mSelectPath);
        }
        mActivity.startActivityForResult(intent, CHOOSE_MUTIL_PHOTOS);
    }

    /**
     * 打开相册
     *
     * @param mActivity
     */
    private void openAlbum(Activity mActivity) {
        DATE = new SimpleDateFormat("yyyy_MMdd_hhmmss").format(new Date());
        if (isSdCardExist()) {
            Intent intent;
            if (Build.VERSION.SDK_INT < 19) {
                intent = new Intent(Intent.ACTION_GET_CONTENT);
                intent.setType("image/*");
            } else {
                intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
            }
            mActivity.startActivityForResult(intent, CHOOSE_PHOTO);
        } else {
            ToastUtils.myToast(mActivity, "请检查您的SD卡是否存在");
        }
    }

    /**
     * 打开相册，选择多张图片
     * @param mActivity
     * @param clazz
     */
//    private  void openMultiAlbum(Activity mActivity,Class clazz){
//        Intent intent = new Intent(mActivity, clazz);
//        // 是否显示拍摄图片,显示
//        intent.putExtra(MultiImageSelectorActivity.EXTRA_SHOW_CAMERA, true);
//        // 最大可选择图片数量 30张
//        intent.putExtra(MultiImageSelectorActivity.EXTRA_SELECT_COUNT, maxNum);
//        // 选择模式,选取多张
//        intent.putExtra(MultiImageSelectorActivity.EXTRA_SELECT_MODE, MultiImageSelectorActivity.MODE_MULTI);
//        // 默认选择
//        if (mSelectPath != null && mSelectPath.size() > 0) {
//            intent.putExtra(MultiImageSelectorActivity.EXTRA_DEFAULT_SELECTED_LIST, mSelectPath);
//        }
//        mActivity.startActivityForResult(intent, REQUEST_MULTI_IMAGE);
//
//    }

    /**
     * 打开相机
     *
     * @param mActivity
     */
    private void openCamera(Activity mActivity) {
        DATE = new SimpleDateFormat("yyyy_MMdd_hhmmss").format(new Date());
        if (isSdCardExist()) {
            photo_image = createImagePath(APP_NAME + DATE);
            File file = new File(photo_image);
            if (!file.getParentFile().exists()) {
                file.getParentFile().mkdirs();
            }
            Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            //Android7.0以上URI
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                //添加这一句表示对目标应用临时授权该Uri所代表的文件
                intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                //通过FileProvider创建一个content类型的Uri
                Uri uri = FileProvider.getUriForFile(mActivity, FILE_CONTENT_FILEPROVIDER, file);
                intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
            } else {
                intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(file));
            }

            mActivity.startActivityForResult(intent, TAKE_PHOTO);
        } else {
            ToastUtils.myToast(mActivity, "请检查您的SD卡是否存在");
        }
    }

    /**
     * 操作之后的回调
     *
     * @param mActivity
     * @param requestCode
     * @param resultCode
     * @param data
     */
    public void onActivityResult(Activity mActivity, int requestCode, int resultCode, Intent data) {

        switch (requestCode) {
            case TAKE_PHOTO:
                //拍照
                try {
//                    String filePath = getRealFilePath(mActivity, imageUri);
                    bitmap = BitmapFactory.decodeFile(photo_image);

                    if (isCrop) {
                        startPhotoZoom(mActivity, photo_image, 350);//去裁剪图片
                    } else {
                        if (bitmap != null && photo_image != null) {
                            photoListener.onSuccess(bitmap, photo_image);

                        } else {
                            photoListener.onFail();
                        }
                    }


                } catch (Exception e) {
                    photoListener.onFail();
                }
                break;
            case CHOOSE_PHOTO:
                try {
                    if (Build.VERSION.SDK_INT >= 19) {
                        photo_image = handleImageOnKitKat(mActivity, data);
                        bitmap = BitmapFactory.decodeFile(photo_image);
                        if (!photo_image.isEmpty() && bitmap != null) {
                            if (isCrop) {
                                startPhotoZoom(mActivity, handleImageOnKitKat(mActivity, data), 350);//压缩图片
                            } else {
                                photoListener.onSuccess(bitmap, photo_image);
                            }

                        }

                    } else {
                        photo_image = handleImageBeforeKitKat(mActivity, data);//获取到图片的路径
                        bitmap = BitmapFactory.decodeFile(photo_image);
                        if (!photo_image.isEmpty() && bitmap != null) {
                            if (isCrop) {
                                startPhotoZoom(mActivity, handleImageBeforeKitKat(mActivity, data), 350);//压缩图片
                            } else {
                                photoListener.onSuccess(bitmap, photo_image);
                            }

                        }

                    }
                } catch (Exception e) {
                    photoListener.onFail();
                }

                break;
            case CROP_PHOTO:
                //裁剪图片
                try {
                    bitmap = BitmapFactory.decodeStream(mActivity.getContentResolver().openInputStream(Uri.fromFile(new File(crop_image))));
                    if (!crop_image.isEmpty() && bitmap != null) {
                        photoListener.onSuccess(bitmap, crop_image);
                    } else {
                        photoListener.onFail();
                    }
                } catch (Exception e) {
                    photoListener.onFail();
                    Log.e("msg", "获取照片出错");
                }
                break;
            case CHOOSE_MUTIL_PHOTOS:
                //选取多张照片
                try {
                    mSelectPath = data.getStringArrayListExtra(MultiImageSelectorActivity.EXTRA_RESULT);
                    if (mSelectPath != null && mSelectPath.size() > 0) {
                        for (String p : mSelectPath) {
                            //加入最后选择的集合
                            finalSelectPaths.add(p);
                            //加载缩略图
                            Bitmap bitmap = BitmapUtils.decodeSampledBitmapFromSd(p, 200, 240);
                            bitmapList.add(bitmap);
                        }
                        photoListener.onSuccess(bitmapList, finalSelectPaths);
                    } else {
                        photoListener.onFail();

                    }
                } catch (Exception e) {
                    photoListener.onFail();
                }


                break;


            default:
                photoListener.onFail();
        }

    }


    @TargetApi(value = 19)
    private static String handleImageOnKitKat(Activity mActivity, Intent data) {
        String imagePath = null;
        Uri uri = data.getData();
        if (DocumentsContract.isDocumentUri(mActivity, uri)) {
            //如果是document类型的uri，则通过document id 处理
            String docId = DocumentsContract.getDocumentId(uri);
            if ("com.android.providers.media.documents".equals(uri.getAuthority())) {
                String id = docId.split(":")[1];//解析出数字格式的id
                String selection = MediaStore.Images.Media._ID + "=" + id;
                imagePath = getImagePath(mActivity, MediaStore.Images.Media.EXTERNAL_CONTENT_URI, selection);
            } else if ("com.android.providers.downloads.documents".equals(uri.getAuthority())) {
                Uri contentUri = ContentUris.withAppendedId(Uri.parse("content://downloads/public_downloads"), Long.valueOf(docId));
                imagePath = getImagePath(mActivity, contentUri, null);
            }
        } else if ("content".equalsIgnoreCase(uri.getScheme())) {
            //如果content类型的uri，则使用普通方式处理
            imagePath = getImagePath(mActivity, uri, null);
        } else if ("file".equalsIgnoreCase(uri.getScheme())) {
            //如果是file类型的uri，直接获取图片路径即可
            imagePath = uri.getPath();
        }
        return imagePath;
//        displayImage(imagePath);
    }

    private static String handleImageBeforeKitKat(Activity mActivity, Intent data) {
        Uri uri = data.getData();
        String imagePath = getImagePath(mActivity, uri, null);
        return imagePath;
//        displayImage(imagePath);
    }

    private static String getImagePath(Activity mActivity, Uri uri, String selection) {
        String path = null;
        //通过Uri和selection来获取真实的图片路径
        Cursor cursor = mActivity.getContentResolver().query(uri, null, selection, null, null);
        if (cursor != null) {
            if (cursor.moveToFirst())
                path = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA));
            cursor.close();
        }
        return path;
    }

    /**
     * 通过路径获取bitmap
     *
     * @param imagePath
     */
    private static void displayImage(String imagePath) {
        if (imagePath != null) {
            Bitmap bitmap = BitmapFactory.decodeFile(imagePath);

        } else {
            Log.e("msg", "获取照片失败");
        }
    }


    /**
     * 剪裁图片
     */
    private void startPhotoZoom(Activity mActivity, String path, int size) {
        File file = new File(path);
        if (!file.getParentFile().exists()) {
            file.getParentFile().mkdirs();
        }
        Uri imageUri;
        Uri outputUri;
        crop_image = createImagePath(APP_NAME + "_crop_" + DATE);

        Intent intent = new Intent("com.android.camera.action.CROP");
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            //添加这一句表示对目标应用临时授权该Uri所代表的文件
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            //通过FileProvider创建一个content类型的Uri
            imageUri = FileProvider.getUriForFile(mActivity, FILE_CONTENT_FILEPROVIDER, file);
            outputUri = Uri.fromFile(new File(crop_image));
            //TODO:outputUri不需要ContentUri,否则失败
            //outputUri = FileProvider.getUriForFile(activity, "com.solux.furniture.fileprovider", new File(crop_image));
        } else {
            imageUri = Uri.fromFile(file);
            outputUri = Uri.fromFile(new File(crop_image));
        }
        intent.setDataAndType(imageUri, "image/*");
        intent.putExtra("crop", "true");
        //设置宽高比例
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);
        //设置裁剪图片宽高
        intent.putExtra("outputX", 300);
        intent.putExtra("outputY", 300);
        intent.putExtra("scale", true);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, outputUri);
        intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
        intent.putExtra("noFaceDetection", true);
        mActivity.startActivityForResult(intent, CROP_PHOTO);
    }

    public static Uri getImageContentUri(Context context, File imageFile) {
        String filePath = imageFile.getAbsolutePath();
        Cursor cursor = context.getContentResolver().query(
                MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                new String[]{MediaStore.Images.Media._ID},
                MediaStore.Images.Media.DATA + "=? ",
                new String[]{filePath}, null);

        if (cursor != null && cursor.moveToFirst()) {
            int id = cursor.getInt(cursor
                    .getColumnIndex(MediaStore.MediaColumns._ID));
            Uri baseUri = Uri.parse("content://media/external/images/media");
            return Uri.withAppendedPath(baseUri, "" + id);
        } else {
            if (imageFile.exists()) {
                ContentValues values = new ContentValues();
                values.put(MediaStore.Images.Media.DATA, filePath);
                return context.getContentResolver().insert(
                        MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
            } else {
                return null;
            }
        }
    }

    /**
     * 根据uri获取文件的真实路径
     *
     * @param context
     * @param uri
     * @return
     */
    public static String getRealFilePath(final Context context, final Uri uri) {
        if (null == uri) return null;
        final String scheme = uri.getScheme();
        String data = null;
        if (scheme == null)
            data = uri.getPath();
        else if (ContentResolver.SCHEME_FILE.equals(scheme)) {
            data = uri.getPath();
        } else if (ContentResolver.SCHEME_CONTENT.equals(scheme)) {
            Cursor cursor = context.getContentResolver().query(uri, new String[]{MediaStore.Images.ImageColumns.DATA}, null, null, null);
            if (null != cursor) {
                if (cursor.moveToFirst()) {
                    int index = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
                    if (index > -1) {
                        data = cursor.getString(index);
                    }
                }
                cursor.close();
            }
        }
        return data;
    }

    private static File getCacheFile(File parent, String child) {
        // 创建File对象，用于存储拍照后的图片
        File file = new File(parent, child);

        if (file.exists()) {
            file.delete();
        }
        try {
            file.createNewFile();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return file;
    }

    public static String getDiskCacheDir(Context context) {
        String cachePath = null;
        if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())
                || !Environment.isExternalStorageRemovable()) {
            cachePath = context.getExternalCacheDir().getPath();
        } else {
            cachePath = context.getCacheDir().getPath();
        }
        return cachePath;
    }

    /**
     * 创建图片的存储路径
     */
    public String createImagePath(String imageName) {
        String dir = PICTURE_DIR;
        File destDir = new File(dir);
        if (!destDir.exists()) {
            destDir.mkdirs();
        }
        File file = null;
        if (!TextUtils.isEmpty(imageName)) {
            file = new File(dir, imageName + ".jpeg");
        }
        return file.getAbsolutePath();
    }

    /**
     * 检查SD卡是否存在
     */
    public boolean isSdCardExist() {
        return Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED);
    }

    public interface PhotoListener {

        void onFail();//获取失败

        void onSuccess(Bitmap bitmap, String filePath);//获取成功

        void onSuccess(List<Bitmap> bitmapList, List<String> filePathList);//多选的回调方法


    }

}
